package com.bnz.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import com.alibaba.fastjson.JSON;
import com.bnz.search.entity.ItemEntity;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
@RabbitListener(queues = "updateStatus")
public class GoodsStatusListener {
	@Autowired
	private ElasticsearchClient client;
	@RabbitHandler
	public void getMessage(String msg) throws IOException {
		//1. 得到要同步的sku商品列表
		List<ItemEntity> itemEntities = JSON.parseArray(msg, ItemEntity.class);
		//2. 同步到es中
		// 处理specMap数据
		for (ItemEntity itemEntity : itemEntities) {
			String spec = itemEntity.getSpec();
			Map map = JSON.parseObject(spec, Map.class);
			itemEntity.setSpecMap(map);
		}
		System.out.println("itemEntities = " + itemEntities);
		//2.2 将上面的列表数据添加到索引库中
		BulkRequest.Builder builder = new BulkRequest.Builder();
		for (ItemEntity itemEntity : itemEntities) {
			builder.operations(ope->ope.index(
					idx->idx.index("item")
							.id(itemEntity.getId() + "")
							.document(itemEntity)
			)) ;
		}
		BulkRequest request = builder.build();
		client.bulk(request);

		System.out.println("审核通过的sku商品添加到索引库成功！");
	}
}
